package com.gsma.calendar.android.util;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.gsma.calendar.android.db.LocalCalendarEventsColumns;
import com.gsma.calendar.android.model.LocalCalendarEvents;

public class UpdateScript {
	private Context context;

	public UpdateScript(Context context) {
		this.context = context;
	}
	
	public void runUpdate() {
		String baseUri = "content://com.android.calendar/events/";

		CalendarGsmaUtil calendarGsmaUtil = new CalendarGsmaUtil(context);
		ArrayList<String> list = new ArrayList<String>();
		Cursor cursor = calendarGsmaUtil.getCalendarManagedCursor(null, null, "events");
		if (cursor != null && cursor.moveToFirst()) {
			do {
				String id = cursor.getString(cursor.getColumnIndex("_id"));
				list.add(baseUri.concat(id));
			} while (cursor.moveToNext());
		}
		String[] remains = list.toArray(new String[list.size()]);

		int count = context.getContentResolver().delete(LocalCalendarEvents.CONTENT_URI,
				LocalCalendarEventsColumns.URI_EVENT.getName() + " not in (" + getPlaceHolder(remains) + ")", remains);
		Log.e("", " " + count);
	}
	
	private String getPlaceHolder(String[] remains) {
		StringBuilder placeHolder = new StringBuilder();

		for (int i = 0; i < remains.length; i++) {
			placeHolder.append("?,");
		}
		// remove last comma
		placeHolder.setLength(placeHolder.length() - 1);
		return placeHolder.toString();
	}
}
